package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import util.Calc;
import util.WxUtil;
import wx.IoUtil;
import wx.MessageHandler;
import wx.MessageUtil;
import wx.NewsMessage;
import wx.NewsMessage.Article;
import wx.WxBot;

/**
 * Servlet implementation class WxInterface
 */
@WebServlet(name = "/WxInterface", loadOnStartup = 1, urlPatterns = "/WxInterface")
public class WxInterface extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public static final boolean ENABLE_ACCESS_TOKEN_MAINTAIN = true;

	// 预读取文本资源
	private String menuTpl = null;
	private String subscribeMessage = null;
	private String bindTip = null;
	private String unbindTip = null;

	public static WxBot wxBot;
	private MessageHandler handler = new MessageHandler(wxBot) {
		public String onTextMessage(java.util.Map<String, String> requestMap) {
			// 发送方帐号
			String fromUserName = requestMap.get("FromUserName");
			// 开发者微信号
			String toUserName = requestMap.get("ToUserName");
			// NetUtil.dumpMap(requestMap);
			String content = requestMap.get("Content");

			// 开始内容逻辑分析
			if (content.startsWith("绑定")) {
				String idField = content.substring(2);
				// try to convert to decimal
				try {
					int id = Integer.parseInt(idField);
					// call bind
					if (util.WxUtil.bind(fromUserName, id + "")) {
						return WxBot.makeSimpleMessage(toUserName, fromUserName, "绑定成功");
					} else {
						return WxBot.makeSimpleMessage(toUserName, fromUserName, "绑定失败！请您确认该控制器是否存在或您是否已绑定了该控制器。");
					}
				} catch (Exception e) {
					// e.printStackTrace();
					return WxBot.makeSimpleMessage(toUserName, fromUserName, "您输入的格式有误，请重新输入");
				}
			} else if (content.startsWith("解绑")) {
				String idField = content.substring(2);
				// try to convert it to decimal
				try {
					int id = Integer.parseInt(idField);
					// call bind
					if (util.WxUtil.unbind(fromUserName, id + "")) {
						return WxBot.makeSimpleMessage(toUserName, fromUserName, "解绑成功");
					} else {
						return WxBot.makeSimpleMessage(toUserName, fromUserName, "解绑失败。请您确认该控制器是否存在或您是否已绑定了该控制器。");
					}
				} catch (Exception e) {
					// e.printStackTrace();
					return WxBot.makeSimpleMessage(toUserName, fromUserName, "您输入的格式有误，请重新输入");
				}
			} else if (content.equals("666")) {
				// 创建图文消息(回复用)
				NewsMessage newsMessage = new NewsMessage();
				newsMessage.setToUserName(fromUserName);
				newsMessage.setFromUserName(toUserName);
				newsMessage.setCreateTime(new Date().getTime());
				newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);

				List<Article> articleList = new ArrayList<Article>();

				Article article = new Article();
				article.setTitle("haojiahong的博客");
				article.setDescription("我不是高手，我不会武功。");
				article.setPicUrl("http://pic.cnblogs.com/avatar/466668/20150530175722.png");
				article.setUrl("http://www.cnblogs.com/haojiahong");
				articleList.add(article);
				// 设置图文消息个数
				newsMessage.setArticleCount(articleList.size());
				// 设置图文消息包含的图文集合
				newsMessage.setArticles(articleList);
				// 将图文消息对象转换成xml字符串
				return MessageUtil.messageToXml(newsMessage);
			} else {
				/*
				 * String result = wxBot.sendTemplateMessage(fromUserName,
				 * "oZ8TbwgPTPVoxD58LMf2qAr3_M6u0sq-GW8TCptSQyU", "http://www.baidu.com", null,
				 * null); System.out.println(result);
				 */
				try {
					double result = Calc.run(content);
					return WxBot.makeSimpleMessage(toUserName, fromUserName, "计算结果：" + result);
				} catch (Exception e) {
				}
				return onEventSubscribeMessage(requestMap);
			}
			// return success
		};

		public String onGetAccessToken(String accesstoken) {
			System.out.println("获取到了Access Token");
			// create menu
			// menuTpl =
			// "{\"button\":[{\"type\":\"click\",\"name\":\"欢迎\",\"key\":\"V1001_BIND\"},{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"},{\"type\":\"click\",\"name\":\"我的设备\",\"key\":\"V1001_DEVICE\"},{\"type\":\"click\",\"name\":\"赞一下\",\"key\":\"V1001_GOOD\"}]}]}";
			// System.out.println(menuTpl);
			String resultMenu = wxBot.setMenu(menuTpl);
			System.out.println("更新菜单请求的返回：" + resultMenu);
			return null;
		};

		public String onEventClickMessage(java.util.Map<String, String> requestMap) {
			// NetUtil.dumpMap(requestMap);
			String eventKey = requestMap.get("EventKey");
			String fromUserName = requestMap.get("FromUserName");
			String toUserName = requestMap.get("ToUserName");
			if (eventKey.equals("V1001_BIND")) {
				String finalBindTip = String.format(bindTip, "http://www.baidu.com/");
				return WxBot.makeSimpleMessage(toUserName, fromUserName, finalBindTip);
			} else if (eventKey.equals("V1001_UNBIND")) {
				String finalUnBindTip = String.format(unbindTip, "http://www.baidu.com/");
				return WxBot.makeSimpleMessage(toUserName, fromUserName, finalUnBindTip);
			} else if (eventKey.equals("V1001_DEVICE")) {
				List<JSONObject> controllers = WxUtil.getControllerListByOpenId(fromUserName);
				StringBuffer sb = new StringBuffer();
				if (0 == controllers.size()) {
					sb.append("您还未绑定控制器！");
				} else {
					sb.append("以下是您绑定的控制器列表：\n");
					try {
						for (JSONObject controller : controllers) {
							sb.append("\n");
							sb.append(controller.get("controllerid"));
							sb.append("（<a href=''>解绑</a>）");
							sb.append("\n");
							sb.append(controller.get("controllername"));
							sb.append("\n");
						}
						sb.append("\n");
						sb.append("共 " + controllers.size() + " 台");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return WxBot.makeSimpleMessage(toUserName, fromUserName, sb.toString());
			}
			return "success";
		};

		public String onEventSubscribeMessage(java.util.Map<String, String> requestMap) {
			// 发送方帐号
			String fromUserName = requestMap.get("FromUserName");
			// 开发者微信号s
			String toUserName = requestMap.get("ToUserName");
			// 回复文本消息
			return WxBot.makeSimpleMessage(toUserName, fromUserName, subscribeMessage);
		};

	};

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public WxInterface() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		wxBot.checkSignature(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		wxBot.processRequest(request, response);
		// doGet(request, response);
	}

	@Override
	public void init() throws ServletException {
		menuTpl = IoUtil.ReadFile(getServletContext().getRealPath("wx/menu.json"));
		subscribeMessage = IoUtil.ReadFile(getServletContext().getRealPath("wx/subscribe.txt"));
		bindTip = IoUtil.ReadFile(getServletContext().getRealPath("wx/bindTip.txt"));
		unbindTip = IoUtil.ReadFile(getServletContext().getRealPath("wx/unbindTip.txt"));

		wxBot = new WxBot("Wang805447391", "wx95bf4741ad8a414b", "620b251ec1ec06d5b9ff5f3620bccd69",
				"HgJOnJqpGgRSjtNbSjzoWYJqJUQ5aGm1tzdmw4pYORp");
		wxBot.setMessageHandler(handler);
		super.init();
	}

	@Override
	public void destroy() {
		wxBot.release();
		super.destroy();
	}
}
